﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TheVerge.Phone.Controls;
using TheVerge.Base;
using TheVerge.Base.Models;

namespace TheVerge.Phone.Pages
{
    public partial class ArticlesPage : BasePage
    {
        private VMEntries<ArticleEntry> VM;
        public ArticlesPage()
        {
            InitializeComponent();
            VM = App.MainVM.Articles;
            VM.Refresh();
            DataContext = VM;
            Loaded += (s, e) => aec.InitArticleViewer(articlesRoot.ActualWidth, articlesRoot.ActualHeight);
            OrientationChanged += (s, e) => aec.InitArticleViewer(articlesRoot.ActualWidth, articlesRoot.ActualHeight);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (aec.IsOverlayVisible)
            {
                aec.HideOverlay();
                e.Cancel = true;
            }
            else if (aec.IsVisible)
            {
                aec.Hide();
                e.Cancel = true;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back && aec.IsVisible)
                aec.Refresh();
        }

        protected override bool IsMini { get { return true; } }

        protected override IEnumerable<IApplicationBarIconButton> Buttons { get { return null; } }

        protected override IEnumerable<IApplicationBarMenuItem> MenuItems
        {
            get
            {
                yield return AppBarHelper.SettingsItem;
                yield return AppBarHelper.LoginItem;
            }
        }

        private void Article_Click(object sender, RoutedEventArgs e)
        {
            var fe = sender as FrameworkElement;
            var article = fe.DataContext as ArticleEntry;

            aec.LoadEntry(article);
        }
    }
}